#!/usr/bin/env python3
"""
工具函数模块
提供通用的工具函数和辅助方法
"""

import logging
from datetime import datetime
from typing import Dict, Any, List

logger = logging.getLogger(__name__)

class AlertUtils:
    """告警工具类"""
    
    @staticmethod
    def format_timestamp(timestamp: int) -> str:
        """格式化时间戳"""
        if timestamp and timestamp > 0:
            return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
        return '未知'
    
    @staticmethod
    def get_severity_name(severity: int) -> str:
        """获取严重程度名称"""
        severity_map = {
            0: "未分类",
            1: "信息",
            2: "警告",
            3: "一般严重",
            4: "严重",
            5: "灾难"
        }
        return severity_map.get(severity, f"未知({severity})")
    
    @staticmethod
    def get_severity_emoji(severity: int) -> str:
        """获取严重程度对应的表情符号"""
        emoji_map = {
            0: "ℹ️",
            1: "ℹ️",
            2: "⚠️",
            3: "🔶",
            4: "🔥",
            5: "💥"
        }
        return emoji_map.get(severity, "❓")
    
    @staticmethod
    def is_critical_alert(alert: Dict[str, Any]) -> bool:
        """判断是否为严重告警（严重级别4以上） - 修复None值问题"""
        severity = alert.get('severity')
        if severity is None:
            return False
        try:
            return int(severity) >= 4
        except (ValueError, TypeError):
            return False
    
    @staticmethod
    def group_alerts_by_host(alerts: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
        """按主机分组告警"""
        grouped = {}
        for alert in alerts:
            host_name = alert.get('host_name', '未知主机')
            if host_name not in grouped:
                grouped[host_name] = []
            grouped[host_name].append(alert)
        return grouped
    
    @staticmethod
    def group_alerts_by_severity(alerts: List[Dict[str, Any]]) -> Dict[int, List[Dict[str, Any]]]:
        """按严重程度分组告警 - 修复None值问题"""
        grouped = {}
        for alert in alerts:
            severity = alert.get('severity')
            if severity is None:
                severity = 0
            else:
                try:
                    severity = int(severity)
                except (ValueError, TypeError):
                    severity = 0
                    
            if severity not in grouped:
                grouped[severity] = []
            grouped[severity].append(alert)
        return grouped
    
    @staticmethod
    def get_alert_duration(alert: Dict[str, Any]) -> str:
        """计算告警持续时间"""
        problem_clock = alert.get('problem_clock')
        if not problem_clock:
            return '未知'
        
        current_time = datetime.now().timestamp()
        duration_seconds = int(current_time - problem_clock)
        
        if duration_seconds < 60:
            return f"{duration_seconds}秒"
        elif duration_seconds < 3600:
            minutes = duration_seconds // 60
            return f"{minutes}分钟"
        elif duration_seconds < 86400:
            hours = duration_seconds // 3600
            minutes = (duration_seconds % 3600) // 60
            return f"{hours}小时{minutes}分钟"
        else:
            days = duration_seconds // 86400
            hours = (duration_seconds % 86400) // 3600
            return f"{days}天{hours}小时"

class ReportFormatter:
    """报告格式化工具类"""
    
    @staticmethod
    def format_alert_summary(alerts: List[Dict[str, Any]]) -> str:
        """格式化告警摘要"""
        if not alerts:
            return "📊 **告警统计**: 当前无告警"
        
        total = len(alerts)
        critical_count = len([a for a in alerts if AlertUtils.is_critical_alert(a)])
        hosts_count = len(set(a.get('host_name', '未知') for a in alerts))
        
        summary = f"📊 **告警统计**: 总计 **{total}** 个告警"
        if critical_count > 0:
            summary += f"，其中 **{critical_count}** 个严重告警"
        summary += f"，影响 **{hosts_count}** 台主机"
        
        return summary
    
    @staticmethod
    def format_top_alerts(alerts: List[Dict[str, Any]], limit: int = 5) -> str:
        """格式化优先处理的告警"""
        if not alerts:
            return ""
        
        # 按严重程度和时间排序
        sorted_alerts = sorted(alerts, key=lambda x: (x.get('severity', 0), x.get('problem_clock', 0)), reverse=True)
        
        result = f"\n🔥 **优先处理告警** (Top {min(limit, len(sorted_alerts))}):\n"
        
        for i, alert in enumerate(sorted_alerts[:limit], 1):
            severity = alert.get('severity', 0)
            emoji = AlertUtils.get_severity_emoji(severity)
            severity_name = AlertUtils.get_severity_name(severity)
            host_name = alert.get('host_name', '未知主机')
            problem_name = alert.get('problem_name', '未知告警')
            duration = AlertUtils.get_alert_duration(alert)
            
            result += f"{i}. {emoji} **[{severity_name}]** {host_name}: {problem_name}\n"
            result += f"   持续时间: {duration}\n"
        
        return result
    
    @staticmethod
    def format_host_summary(alerts: List[Dict[str, Any]]) -> str:
        """格式化主机告警摘要"""
        grouped = AlertUtils.group_alerts_by_host(alerts)
        
        if not grouped:
            return ""
        
        result = f"\n🖥️ **主机告警分布**:\n"
        
        # 按告警数量排序
        sorted_hosts = sorted(grouped.items(), key=lambda x: len(x[1]), reverse=True)
        
        for host, host_alerts in sorted_hosts[:10]:  # 最多显示10台主机
            critical_count = len([a for a in host_alerts if AlertUtils.is_critical_alert(a)])
            total_count = len(host_alerts)
            
            result += f"- **{host}**: {total_count} 个告警"
            if critical_count > 0:
                result += f" (其中 {critical_count} 个严重)"
            result += "\n"
        
        return result

class LogUtils:
    """日志工具类"""
    
    @staticmethod
    def log_operation_start(operation: str):
        """记录操作开始"""
        logger.info(f"🚀 开始执行: {operation}")
    
    @staticmethod
    def log_operation_success(operation: str, details: str = ""):
        """记录操作成功"""
        message = f"✅ 完成: {operation}"
        if details:
            message += f" - {details}"
        logger.info(message)
    
    @staticmethod
    def log_operation_error(operation: str, error: str):
        """记录操作错误"""
        logger.error(f"❌ 失败: {operation} - {error}")
    
    @staticmethod
    def log_database_stats(db_type: str, alerts_count: int):
        """记录数据库统计信息"""
        logger.info(f"📊 数据库查询完成: {alerts_count} 条告警记录")
    
    @staticmethod
    def log_task_completion(task_name: str):
        """记录任务完成"""
        logger.info(f"🎯 {task_name} - 任务完成")